<script lang="ts">
  import { Events } from "@sparrow/common/enums/mixpanel-events.enum";
  import MixpanelEvent from "@app/utils/mixpanel/MixpanelEvent";
  import { HttpRequestDefaultNameBaseEnum } from "@sparrow/common/types/workspace/http-request-base";
  import { slide } from "svelte/transition";
  import { captureEvent } from "@app/utils/posthog/posthogConfig";
  import { notifications } from "@sparrow/library/ui";
  export let onItemCreated: (entityType: string, args: any) => void;
  export let onItemDeleted: (entityType: string, args: any) => void;
  export let onItemRenamed: (entityType: string, args: any) => void;
  export let onItemOpened: (entityType: string, args: any) => void;
  export let onItemMoved: (args: any) => void;
  export let onBranchSwitched: (collection: CollectionBaseInterface) => any;
  export let onRefetchCollection: (
    workspaceId: string,
    collection: CollectionBaseInterface,
  ) => void;
  export let activeTabPath: Path;
  export let activeTabId: string;
  export let userRoleInWorkspace: WorkspaceRole;
  export let collection: CollectionBaseInterface;
  export let searchData = "";
  export let activeTabType;
  /**
   * Role of user in active workspace
   */
  export let userRole;
  export let isWebApp = false;
  export let isFirstCollectionExpand = false;
  export let onCompareCollection;
  export let onSyncCollection;
  export let isSharedWorkspace = false;
  let isSyncChangesAvailable = false;
  export let isMockCollection = false;
  export let onUpdateRunningState;
  export let onCreateMockCollection: (
    collectionId: string,
    workspaceId: string,
  ) => void;
  export let isGuestUser = false;

  import {
    openedComponent,
    addCollectionItem,
    removeCollectionItem,
  } from "../../../../stores/recent-left-panel";
  import { setOverForbiddenZone } from "../../../../stores/drag-state";

  import { angleRightV2Icon as angleRight } from "@sparrow/library/assets";
  import { dot3Icon as threedotIcon } from "@sparrow/library/assets";
  import {
    ItemType,
    UntrackedItems,
  } from "@sparrow/common/enums/item-type.enum";
  import { Spinner, Tag } from "@sparrow/library/ui";
  import { onDestroy, onMount } from "svelte";
  import { Modal } from "@sparrow/library/ui";
  import { Button } from "@sparrow/library/ui";
  import { WorkspaceRole } from "@sparrow/common/enums";
  import { Tooltip } from "@sparrow/library/ui";
  import { gitBranchIcon } from "@sparrow/library/assets";
  import { ReloadCollectionIcon } from "@sparrow/library/assets";
  import Folder from "../folder/Folder.svelte";
  import type { Path } from "@sparrow/common/interfaces/request.interface";
  import { addIcon as AddIcon } from "@sparrow/library/assets";
  import {
    FolderIcon,
    SyncIcon,
    FolderPlusIcon,
    RequestIcon,
    SocketIcon,
    SocketIoIcon,
    GraphIcon,
    DismissRegular,
    AddRegular,
    ChevronRightRegular,
    ChevronDownRegular,
    MoreHorizontalRegular,
    FolderAddRegular,
    ArrowSwapRegular,
    RecordStopRegular,
    PlayCircleRegular,
    SettingsRegular,
    HistoryRegular,
    CircleSmallFilled,
    BotRegular,
  } from "@sparrow/library/icons";
  import { Options } from "@sparrow/library/ui";
  import { SocketIORequestDefaultAliasBaseEnum } from "@sparrow/common/types/workspace/socket-io-request-base";
  import { GraphqlRequestDefaultAliasBaseEnum } from "@sparrow/common/types/workspace/graphql-request-base";
  import type { CollectionBaseInterface } from "@sparrow/common/types/workspace/collection-base";
  import { CollectionNavigationTabEnum } from "@sparrow/common/types/workspace/collection-tab";
  import {
    activeSyncStore,
    updateActiveSyncStates,
  } from "../../../../stores/active-sync";
  import { inview } from "svelte-inview";

  export let visibility = false;
  let deletedIds: string[] = [];
  let requestCount = 0;
  let folderCount = 0;
  let graphQLCount = 0;
  let webSocketCount = 0;
  let socketIoCount = 0;
  let mockRequestCount = 0;
  let aiRequestCount = 0;
  let isActiveSyncEnabled = true;
  let isBranchSynced: boolean = false;
  let isRenaming = false;
  let activeSyncLoad: boolean = false;
  let isSyncBtnHovered = false;
  let isCollectionPopup: boolean = false;
  let showMenu: boolean = false;
  let showAddItemMenu = false;
  let noOfColumns = 180;
  let inputField: HTMLInputElement;
  let collectionTabWrapper: HTMLElement;
  let isEnableSyncButton = false;
  let isSyncing = false;
  let showMockMenu: boolean = false;

  // let visibleExplorers = [];
  // const renderBatchSize = 10;

  // function waitNextFrames(frameCount = 1): Promise<void> {
  //   return new Promise((resolve) => {
  //     function next(n: number) {
  //       if (n <= 0) return resolve();
  //       requestAnimationFrame(() => next(n - 1));
  //     }
  //     next(frameCount);
  //   });
  // }

  // async function renderExplorersInBatches(items: any[], batchSize = 10) {
  //   visibleExplorers = [];

  //   for (let i = 0; i < items.length; i += batchSize) {
  //     visibleExplorers = [
  //       ...visibleExplorers,
  //       ...items.slice(i, i + batchSize),
  //     ];
  //     if (searchData) {
  //       await waitNextFrames(100); // let UI update
  //     } else {
  //       await waitNextFrames(10); // let UI update
  //     }
  //   }
  // }

  // $: if (visibility && collection?.items?.length) {
  //   renderExplorersInBatches(collection.items, renderBatchSize);
  // }

  /**
   * Handle position of the context menu
   */
  const rightClickContextMenu = () => {
    setTimeout(() => {
      showMenu = !showMenu;
    }, 100);
  };

  const rightClickContextMenuMock = () => {
    setTimeout(() => {
      showMockMenu = !showMockMenu;
    }, 100);
  };

  const rightClickContextMenu2 = () => {
    setTimeout(() => {
      showAddItemMenu = !showAddItemMenu;
    }, 100);
  };

  const handlecollection_set_auth = ({
    event_name,
  }: {
    event_name: string;
  }) => {
    captureEvent("open_collection_auth", {
      component: "Collection",
      button_text: event_name,
      destination: event_name,
    });
  };
  const handleSelectClick = (event: MouseEvent) => {
    const selectElement = document.getElementById(
      `show-more-collection-${collection.id}`,
    );
    if (selectElement && !selectElement.contains(event.target as Node)) {
      showMenu = false;
      showMockMenu = false;
    }
  };

  const handleSelectClick2 = (event: MouseEvent) => {
    const selectElement = document.getElementById(
      `add-item-collection-${collection.id}`,
    );
    if (selectElement && !selectElement.contains(event.target as Node)) {
      showAddItemMenu = false;
    }
  };

  /**
   * Handle selected methods from filter
   */
  // const selectedMethodUnsubscibe = selectMethodsStore.subscribe((value) => {
  //   if (value && value.length > 0) {
  //     showFolderAPIButtons = false;
  //     visibility = true;
  //   } else if (value && value.length === 0) {
  //     visibility = false;
  //   } else {
  //     showFolderAPIButtons = true;
  //   }
  // });
  onDestroy(() => {
    // selectedMethodUnsubscibe();
  });

  let prevActiveTabPath = "";
  $: {
    if (searchData) {
      // addCollectionItem(collection.id, "collection");
    }
    // if (activeTabPath) {
    //   if ((prevActiveTabPath || "") !== (activeTabPath?.collectionId || "")) {
    //     if (activeTabPath.collectionId === collection.id) {
    //       setTimeout(() => {
    //         if (!visibility) {
    //           addCollectionItem(collection.id, "collection");
    //         }
    //       }, 3000);
    //     }
    //   }
    //   prevActiveTabPath = activeTabPath.collectionId;
    // }
  }

  $: {
    if (isCollectionPopup) {
      if (collection) {
        deletedIds = [];
        requestCount = 0;
        mockRequestCount = 0;
        aiRequestCount = 0;
        folderCount = 0;
        graphQLCount = 0;
        webSocketCount = 0;
        socketIoCount = 0;
        collection?.items?.forEach((item: any) => {
          if (item.type === ItemType.FOLDER) {
            deletedIds.push(item.id);
            folderCount++;

            for (let i = 0; i < item.items.length; i++) {
              if (item.items[i].type === ItemType.REQUEST) {
                requestCount++;
                deletedIds.push(item.items[i].id);
              } else if (item.items[i].type === ItemType.GRAPHQL) {
                graphQLCount++;
                deletedIds.push(item.items[i].id);
              } else if (item.items[i].type === ItemType.WEB_SOCKET) {
                webSocketCount++;
                deletedIds.push(item.items[i].id);
              } else if (item.items[i].type === ItemType.SOCKET_IO) {
                socketIoCount++;
                deletedIds.push(item.items[i].id);
              } else if (item.items[i].type === ItemType.MOCK_REQUEST) {
                mockRequestCount++;
                deletedIds.push(item.items[i].id);
              } else if (item.items[i].type === ItemType.AI_REQUEST) {
                aiRequestCount++;
                deletedIds.push(item.items[i].id);
              }
            }
          } else if (item.type === ItemType.REQUEST) {
            requestCount++;
            deletedIds.push(item.id);
          } else if (item.type === ItemType.GRAPHQL) {
            graphQLCount++;
            deletedIds.push(item.id);
          } else if (item.type === ItemType.SOCKET_IO) {
            socketIoCount++;
            deletedIds.push(item.id);
          } else if (item.type === ItemType.WEB_SOCKET) {
            webSocketCount++;
            deletedIds.push(item.id);
          } else if (item.type === ItemType.MOCK_REQUEST) {
            mockRequestCount++;
            deletedIds.push(item.id);
          } else if (item.type === ItemType.AI_REQUEST) {
            aiRequestCount++;
            deletedIds.push(item.id);
          }
        });
        deletedIds.push(collection.id);
      }
    }
  }

  onMount(async () => {
    if (collection?.activeSync) {
      // let response = await onBranchSwitched(collection);
      // if (response) {
      //   isBranchSynced = response.isBranchSynced;
      //   activeSyncLoad = response.activeSyncLoad;
      // }
    }
    // isActiveSyncEnabled = await commonService.isFeatureEnabled(
    //   "isActiveSyncEnabled",
    // );
  });

  let prevCurrentBranch = "";
  let prevBranches = "";
  let activeSyncChanges = {
    addedCount: 0,
    deletedCount: 0,
    modifiedCount: 0,
    percentChange: 0,
    added: [],
    deleted: [],
    modified: [],
  };
  // $: {
  //   if (collection?.activeSync && collection?.currentBranch) {
  //     if (collection.currentBranch !== prevCurrentBranch) {
  //       onBranchSwitched(collection);
  //     }
  //     prevCurrentBranch = collection.currentBranch;
  //   }
  //   if (collection?.activeSync && collection?.branches) {
  //     if (JSON.stringify(collection.branches) !== prevBranches) {
  //       onBranchSwitched(collection);
  //     }
  //     prevBranches = JSON.stringify(collection.branches);
  //   }
  // }

  let deleteLoader: boolean = false;
  let refreshCollectionLoader = false;
  let newCollectionName: string = "";
  let isDragOver = false;
  let isForbiddenDrop = false;

  // Drag and Drop Handlers for Request
  function handleDragOver(event: DragEvent) {
    event.preventDefault();

    // Reject all drops if this collection has activeSync enabled
    if (collection.activeSync) {
      isDragOver = false;
      isForbiddenDrop = true;
      setOverForbiddenZone(true);
      if (event.dataTransfer) {
        event.dataTransfer.dropEffect = "none";
      }
      return;
    }

    try {
      // getData doesn't work in dragover, use sessionStorage
      const dataStr =
        typeof sessionStorage !== "undefined"
          ? sessionStorage.getItem("sparrow-drag-data")
          : null;
      if (!dataStr) {
        isDragOver = false;
        isForbiddenDrop = false;
        return;
      }

      const dragData = JSON.parse(dataStr);
      const targetIsMock = isMockCollection === true;

      // Restrict mock collection cross-moves: cannot move into or out of a mock collection except within same collection
      if (
        (dragData.isMockCollection || targetIsMock) &&
        dragData.collectionId !== collection.id
      ) {
        isDragOver = false;
        isForbiddenDrop = true;
        setOverForbiddenZone(true);
        if (event.dataTransfer) {
          event.dataTransfer.dropEffect = "none";
        }
        return;
      }

      // Reject drops from activeSync collections
      if (dragData.collectionActiveSync) {
        isDragOver = false;
        isForbiddenDrop = true;
        setOverForbiddenZone(true);
        if (event.dataTransfer) {
          event.dataTransfer.dropEffect = "none";
        }
        return;
      }

      // Check if dropping from same collection root to same collection root (forbidden)
      if (dragData.collectionId === collection.id && !dragData.folderId) {
        isDragOver = false;
        isForbiddenDrop = true;
        setOverForbiddenZone(true);
        if (event.dataTransfer) {
          event.dataTransfer.dropEffect = "none";
        }
      } else {
        isDragOver = true;
        isForbiddenDrop = false;
        setOverForbiddenZone(false);
        if (event.dataTransfer) {
          event.dataTransfer.dropEffect = "move";
        }
      }
    } catch (e) {
      isDragOver = false;
      isForbiddenDrop = false;
    }
  }

  function handleDragLeave(event: DragEvent) {
    isDragOver = false;
    isForbiddenDrop = false;
    setOverForbiddenZone(false);
  }

  async function handleDrop(event: DragEvent) {
    event.preventDefault();
    isDragOver = false;
    isForbiddenDrop = false;

    // Reject all drops if this collection has activeSync enabled
    if (collection.activeSync) {
      return;
    }

    try {
      const data = event.dataTransfer?.getData("text/plain");
      if (!data) return;
      const dragData = JSON.parse(data);
      const targetIsMock = isMockCollection === true;

      if (
        (dragData.isMockCollection || targetIsMock) &&
        dragData.collectionId !== collection.id
      ) {
        return; // Block cross-collection mock moves
      }

      // Reject drops from activeSync collections
      if (dragData.collectionActiveSync) {
        return;
      }

      // Don't allow dropping from same collection root to same collection root
      if (dragData.collectionId === collection.id && !dragData.folderId) {
        return;
      }

      // Only allow dropping requests (not folders)
      if (dragData.requestId) {
        // Call parent handler to move the request to collection root (no folder)
        onItemMoved &&
          onItemMoved({
            oldCollectionId: dragData.collectionId,
            newCollectionId: collection.id,
            oldFolderId: dragData.folderId,
            newFolderId: "", // Moving to collection root
            requestId: dragData.requestId,
          });
      }
    } catch (e) {
      // Optionally handle error
    }
  }

  const handleRenameInput = (event: Event) => {
    const target = event.target as HTMLInputElement;
    newCollectionName = target.value.trim();
  };

  const isValidCollectionName = (name: string) => {
    const trimmedName = name.trim();
    // Check if empty
    if (!trimmedName) return false;
    // Check if contains at least one alphanumeric character
    const hasAlphanumeric = /[a-zA-Z0-9]/.test(trimmedName);
    // Check if contains only allowed characters (letters, digits, spaces, ., -, _)
    const onlyAllowedChars = /^[a-zA-Z0-9._\- ]+$/.test(trimmedName);
    return hasAlphanumeric && onlyAllowedChars;
  };

  const onRenameBlur = async () => {
    if (newCollectionName) {
      if (!isValidCollectionName(newCollectionName)) {
        notifications.error(
          "Collection names can contain combination of letters, digits and these special characters (.,-,_). Please provide the collection names accordingly.",
        );
        isRenaming = false;
        newCollectionName = "";
        return;
      }
      await onItemRenamed("collection", {
        workspaceId: collection.workspaceId,
        collection,
        newName: newCollectionName,
      });
    }
    isRenaming = false;
    newCollectionName = "";
  };

  const onRenameInputKeyPress = (event: { key: string }) => {
    if (event.key === "Enter") {
      const inputField = document.getElementById(
        "renameInputFieldCollection",
      ) as HTMLInputElement;
      inputField.blur();
    }
  };

  let verticalCollectionLine = false;
  $: {
    if (collection.items.find((item) => item.id === activeTabId)) {
      verticalCollectionLine = true;
    } else {
      verticalCollectionLine = false;
    }
  }

  let intervalId;

  onMount(async () => {
    // Call it once immediately
    activeSyncChanges = await onCompareCollection(collection.id);

    // Set interval and save its ID
    intervalId = setInterval(
      () => {
        onCompareCollection(collection.id)
          .then((result) => {
            activeSyncChanges = result;
            if (activeSyncChanges.percentChange > 0) {
              // isSyncChangesAvailable = true;
              updateActiveSyncStates(collection.id, {
                isChangesAvailable: true,
                isloading: false,
              });
              isEnableSyncButton = true;
            }
          })
          .catch((error) => {
            console.error("Error during interval compare:", error);
          });
      },
      1 * 60 * 1000,
    ); // 2 minutes

    // Optional: cleanup right here if component is destroyed
    return () => {
      clearInterval(intervalId);
    };
  });

  const activeSyncStoreSubscriber = activeSyncStore.subscribe((syncState) => {
    const state = syncState.get(collection.id);
    if (state) {
      isSyncChangesAvailable = state.isChangesAvailable;
      isSyncing = state.isloading;
    }
  });

  onDestroy(() => {
    clearInterval(intervalId); // Clean-up to avoid memory leaks
    activeSyncStoreSubscriber();
  });

  let isMockRunning = false;
  const mockRunningStatus = () => {
    onUpdateRunningState(collection.id, collection.workspaceId, {
      isMockCollectionRunning: !collection?.isMockCollectionRunning,
    });
    isMockRunning = !isMockRunning;
  };

  let isInView: boolean = false;
  let scrollDirection: ScrollDirection | any;
  const options: Options = {
    rootMargin: "0px",
    unobserveOnEnter: true,
    threshold: 0.5,
  };

  const handleChange = ({ detail }: CustomEvent<ObserverEventDetails>) => {
    isInView = detail.inView;
    scrollDirection = detail?.scrollDirection?.vertical;
  };
</script>

<svelte:window
  on:click={handleSelectClick}
  on:contextmenu|preventDefault={handleSelectClick}
  on:click={handleSelectClick2}
  on:contextmenu|preventDefault={handleSelectClick2}
/>

<Modal
  title={isMockCollection ? "Delete Mock Collection" : "Delete Collection?"}
  type={"danger"}
  width={"35%"}
  zIndex={1000}
  isOpen={isCollectionPopup}
  handleModalState={() => (isCollectionPopup = false)}
>
  <div class="text-lightGray mb-1 {isMockCollection ? 'mt-3' : ''}">
    <p
      class="text-ds-font-size-14 text-ds-line-height-120 text-ds-font-weight-medium"
    >
      Are you sure you want to delete this {isMockCollection
        ? "mock collection"
        : "Collection"}? Everything in
      <span
        class="text-ds-font-weight-semi-bold"
        style="color: var(--text-ds-neutral-50);">"{collection.name}"</span
      >
      will be removed.
    </p>
  </div>
  <div class="d-flex flex-wrap gap-3">
    <div class="d-flex gap-1 text-ds-font-size-12">
      <span class="text-plusButton">{folderCount}</span>
      <p>Folder</p>
    </div>
    {#if !isMockCollection}
      <div class="d-flex gap-1 text-ds-font-size-12">
        <span class="text-plusButton">{requestCount}</span>
        <p>{HttpRequestDefaultNameBaseEnum.NAME}</p>
      </div>
      <div class="d-flex gap-1 text-ds-font-size-12">
        <span class="text-plusButton">{graphQLCount}</span>
        <p>GraphQL</p>
      </div>
      <div class="d-flex gap-1 text-ds-font-size-12">
        <span class="text-plusButton">{webSocketCount}</span>
        <p>WebSocket</p>
      </div>
      <div class="d-flex gap-1 text-ds-font-size-12">
        <span class="text-plusButton">{socketIoCount}</span>
        <p>Socket.IO</p>
      </div>
      <div class="d-flex gap-1 text-ds-font-size-12">
        <span class="text-plusButton">{aiRequestCount}</span>
        <p>AI Request</p>
      </div>
    {:else}
      <div class="d-flex gap-1 text-ds-font-size-12">
        <span class="text-plusButton">{mockRequestCount}</span>
        <p>{HttpRequestDefaultNameBaseEnum.NAME}</p>
      </div>
    {/if}
  </div>
  <div
    class="d-flex align-items-center justify-content-end gap-3 mt-1 mb-0 rounded"
  >
    <Button
      disable={deleteLoader}
      title={"Cancel"}
      textStyleProp={"font-size: var(--base-text)"}
      type={"secondary"}
      loader={false}
      onClick={() => {
        isCollectionPopup = false;
      }}
    />

    <Button
      disable={deleteLoader}
      title={"Delete"}
      textStyleProp={"font-size: var(--base-text)"}
      loaderSize={18}
      type={"danger"}
      loader={deleteLoader}
      onClick={() => {
        onItemDeleted("collection", {
          workspaceId: collection.workspaceId,
          collection,
          deletedIds,
        });
        isCollectionPopup = false;
      }}
    />
  </div></Modal
>

{#if showMenu && userRole !== WorkspaceRole.WORKSPACE_VIEWER && !isSharedWorkspace}
  <Options
    xAxis={collection.activeSync
      ? collectionTabWrapper.getBoundingClientRect().right - 115
      : collectionTabWrapper.getBoundingClientRect().right - 30}
    yAxis={[
      collectionTabWrapper.getBoundingClientRect().top - 5,
      collectionTabWrapper.getBoundingClientRect().bottom + 5,
    ]}
    zIndex={700}
    menuItems={[
      {
        onClick: () =>
          onItemOpened("collection", {
            workspaceId: collection.workspaceId,
            collection,
          }),
        displayText: "Open Collection",
        disabled: false,
        hidden: false,
      },
      {
        onClick: () => {
          (isRenaming = true), setTimeout(() => inputField.focus(), 100);
        },
        displayText: "Rename Collection",
        disabled: false,
        hidden: false,
        // hidden:
        //   !(collection?.activeSync && isBranchSynced) &&
        //   !(collection?.activeSync && !isBranchSynced)
        //     ? false
        //     : true,
      },
      {
        onClick: () => {
          onCreateMockCollection(collection.id, collection.workspaceId);
        },
        displayText: "Create Mock Collection",
        disabled: false,
        hidden: isGuestUser ? true : false,
      },
      {
        onClick: () => {
          onItemOpened("collection", {
            workspaceId: collection.workspaceId,
            collection,
            navigation: CollectionNavigationTabEnum.AUTH,
          });
          handlecollection_set_auth({ event_name: "Set Auth Clicked" });
        },
        displayText: "Set Auth",
        disabled: false,
        hidden: false,
      },
      {
        onClick: () => {
          isCollectionPopup = true;
        },
        displayText: "Delete",
        disabled: false,
        hidden: false,
      },
    ]}
  />
{/if}

{#if showMockMenu && userRole !== WorkspaceRole.WORKSPACE_VIEWER && !isSharedWorkspace}
  <Options
    xAxis={collection.activeSync
      ? collectionTabWrapper.getBoundingClientRect().right - 115
      : collectionTabWrapper.getBoundingClientRect().right - 30}
    yAxis={[
      collectionTabWrapper.getBoundingClientRect().top - 5,
      collectionTabWrapper.getBoundingClientRect().bottom + 5,
    ]}
    zIndex={700}
    menuItems={[
      {
        onClick: () =>
          onItemOpened("collection", {
            workspaceId: collection.workspaceId,
            collection,
          }),
        displayText: "Open Mock Collection",
        disabled: false,
        hidden: false,
      },
      {
        onClick: () => {
          onItemCreated("folder", {
            workspaceId: collection.workspaceId,
            collection,
          });
        },
        displayText: "Add Folder",
        disabled: false,
        hidden: false,
      },
      {
        onClick: () => {
          onItemCreated("mockRequestCollection", {
            workspaceId: collection.workspaceId,
            collection,
          });
        },
        displayText: `Add Mock ${HttpRequestDefaultNameBaseEnum.NAME}`,
        disabled: false,
        hidden: false,
      },
      {
        onClick: () => {
          (isRenaming = true), setTimeout(() => inputField.focus(), 100);
        },
        displayText: "Rename Mock Collection",
        disabled: false,
        hidden: false,
        // hidden:
        //   !(collection?.activeSync && isBranchSynced) &&
        //   !(collection?.activeSync && !isBranchSynced)
        //     ? false
        //     : true,
      },
      {
        onClick: () => {
          isCollectionPopup = true;
        },
        displayText: "Delete",
        disabled: false,
        hidden: false,
      },
    ]}
  />
{/if}

{#if showAddItemMenu}
  <Options
    xAxis={collectionTabWrapper.getBoundingClientRect().right - 55}
    yAxis={[
      collectionTabWrapper.getBoundingClientRect().top - 5,
      collectionTabWrapper.getBoundingClientRect().bottom + 5,
    ]}
    zIndex={700}
    menuItems={[
      {
        onClick: () => {
          onItemCreated("folder", {
            workspaceId: collection.workspaceId,
            collection,
          });
        },
        displayText: "Add Folder",
        disabled: false,
        hidden: false,
        icon: FolderIcon,
      },
      {
        onClick: () => {
          onItemCreated("requestCollection", {
            workspaceId: collection.workspaceId,
            collection,
          });
        },
        displayText: `Add ${HttpRequestDefaultNameBaseEnum.NAME}`,
        disabled: false,
        hidden: false,
        icon: SyncIcon,
      },
      {
        onClick: () => {
          onItemCreated("websocketCollection", {
            workspaceId: collection.workspaceId,
            collection,
          });
        },
        displayText: "Add WebSocket",
        disabled: false,
        hidden: false,
        icon: SocketIcon,
      },
      {
        onClick: () => {
          onItemCreated("socketioCollection", {
            workspaceId: collection.workspaceId,
            collection,
          });
        },
        displayText: `Add ${SocketIORequestDefaultAliasBaseEnum.NAME}`,
        disabled: false,
        hidden: false,
        icon: SocketIoIcon,
      },
      {
        onClick: () => {
          onItemCreated("graphqlCollection", {
            workspaceId: collection.workspaceId,
            collection,
          });
        },
        displayText: `Add ${GraphqlRequestDefaultAliasBaseEnum.NAME}`,
        disabled: false,
        hidden: false,
        icon: GraphIcon,
      },
      {
        onClick: () => {
          onItemCreated("aiRequestCollection", {
            workspaceId: collection.workspaceId,
            collection,
          });
        },
        displayText: "Add AI Request",
        disabled: false,
        hidden: false,
        icon: BotRegular,
      },
    ]}
  />
{/if}

<div use:inview={options} on:inview_change={handleChange}>
  {#if true}
    <div
      tabindex="0"
      bind:this={collectionTabWrapper}
      style="height:32px; gap:4px;  padding-left:16px; margin-bottom:{collection.id ===
      activeTabId
        ? '0px'
        : '0px'};"
      class="btn-primary d-flex w-100 align-items-center justify-content-between border-0 my-button {collection.id ===
      activeTabId
        ? 'active-collection-tab'
        : ''} {isDragOver ? 'valid-drop-zone' : ''} {isForbiddenDrop
        ? 'drag-forbidden'
        : ''}"
      on:dragover={handleDragOver}
      on:dragleave={handleDragLeave}
      on:drop={handleDrop}
    >
      <button
        tabindex="-1"
        class="d-flex {collection?.activeSync
          ? 'main-collection-sync'
          : isMockCollection
            ? 'main-collection-mock'
            : 'main-collection'} align-items-center bg-transparent border-0 gap:2px;"
        style="gap:4px;"
        on:contextmenu|preventDefault={isMockCollection
          ? rightClickContextMenuMock
          : rightClickContextMenu}
        on:click|preventDefault={() => {
          if (isFirstCollectionExpand) {
            isFirstCollectionExpand = false;
          }
          if (!isRenaming) {
            if (!collection.id.includes(UntrackedItems.UNTRACKED)) {
              if (visibility) {
                removeCollectionItem(collection.id);
              } else {
                addCollectionItem(collection.id, "collection");
                onItemOpened("collection", {
                  workspaceId: collection.workspaceId,
                  collection,
                });
              }
            }
          }
        }}
      >
        <Button
          size="extra-small"
          customWidth={"24px"}
          type="teritiary-regular"
          startIcon={!visibility ? ChevronRightRegular : ChevronDownRegular}
          onClick={(e) => {
            e.stopPropagation();
            if (!isRenaming) {
              if (!collection.id.includes(UntrackedItems.UNTRACKED)) {
                if (visibility) {
                  removeCollectionItem(collection.id);
                } else {
                  addCollectionItem(collection.id, "collection");
                }
              }
            }
          }}
        />
        {#if isRenaming}
          <input
            class="py-0 renameInputFieldCollection w-100 ellipsis text-ds-font-size-12 text-ds-line-height-130 text-ds-font-weight-medium"
            id="renameInputFieldCollection"
            type="text"
            style=" gap: 4px; "
            value={collection.name}
            maxlength={100}
            bind:this={inputField}
            on:click|stopPropagation={() => {}}
            on:input={handleRenameInput}
            on:blur={onRenameBlur}
            on:keydown={onRenameInputKeyPress}
          />
        {:else}
          <div
            class="collection-collection-name justify-content-center d-flex py-1 mb-0 flex-column"
            style="height: 32px; text-align: left; width:80% ; padding:2px 4px;"
          >
            <p
              class="ellipsis mb-0 text-ds-font-size-12 text-ds-line-height-130 text-ds-font-weight-medium"
            >
              {collection.name}
            </p>
            <!-- {#if collection.activeSync}
            <span
              class="text-muted small w-100 ellipsis"
              style="font-size: 0.5rem;"
              ><img src={gitBranchIcon} alt="" />
              {collection?.currentBranch
                ? collection?.currentBranch
                : collection?.primaryBranch}
              {collection?.currentBranch
                ? collection?.currentBranch === collection?.primaryBranch
                  ? "(Default)"
                  : ""
                : "(Default)"}
            </span>
          {/if} -->
          </div>
        {/if}
      </button>
      {#if collection && collection.id && collection.id.includes(UntrackedItems.UNTRACKED)}
        <Spinner size={"15px"} />
      {:else}
        <!-- <Tooltip
        placement="bottom-center"
        title="More options"
        styleProp="bottom: -8px; {!collection?.activeSync ? 'left: -50%' : ''}"
        > -->
        {#if isMockCollection}
          <!-- Mock Tag - shows to everyone -->
          <Tooltip
            title={"This mock collection is inactive. Run it to activate."}
            placement={"top-center"}
            distance={13}
            show={!collection?.isMockCollectionRunning}
            zIndex={701}
          >
            <div style="display: flex;">
              <Tag
                type={collection?.isMockCollectionRunning ? "green" : "grey"}
                text={"Mock"}
              />
            </div>
          </Tooltip>

          <!-- Mock buttons - only for authorized users -->
          {#if userRole !== WorkspaceRole.WORKSPACE_VIEWER && !isSharedWorkspace}
            <Tooltip
              title={collection?.isMockCollectionRunning
                ? "Stop Mock"
                : "Run Mock"}
              placement={"top-center"}
              distance={13}
              zIndex={701}
            >
              <span class="add-icon-container">
                <Button
                  id={`add-item-collection-${collection.id}`}
                  size="extra-small"
                  customWidth={"24px"}
                  type="teritiary-regular"
                  onClick={() => {
                    mockRunningStatus();
                  }}
                  startIcon={collection?.isMockCollectionRunning
                    ? RecordStopRegular
                    : PlayCircleRegular}
                />
              </span>
            </Tooltip>

            <Tooltip
              title={"Add Options"}
              placement={"bottom-center"}
              distance={17}
              zIndex={701}
              show={!showMockMenu}
            >
              <span class="add-icon-container">
                <Button
                  id={`show-more-collection-${collection.id}`}
                  size="extra-small"
                  customWidth={"24px"}
                  type="teritiary-regular"
                  startIcon={MoreHorizontalRegular}
                  onClick={(e) => {
                    rightClickContextMenuMock();
                  }}
                />
              </span>
            </Tooltip>
          {/if}
        {:else}
          <!-- Regular collection buttons -->
          {#if userRole !== WorkspaceRole.WORKSPACE_VIEWER && !isSharedWorkspace}
            {#if !collection?.activeSync}
              <Tooltip
                title={"Add Options"}
                placement={"bottom-center"}
                distance={13}
                show={!showAddItemMenu}
                zIndex={701}
              >
                <span class="add-icon-container">
                  <Button
                    id={`add-item-collection-${collection.id}`}
                    size="extra-small"
                    customWidth={"24px"}
                    type="teritiary-regular"
                    onClick={(e) => {
                      rightClickContextMenu2(e);
                    }}
                    startIcon={AddRegular}
                  />
                </span>
              </Tooltip>
            {/if}

            <Tooltip
              title={"More"}
              placement={"bottom-center"}
              distance={17}
              zIndex={701}
              show={!showMenu}
            >
              <span class="add-icon-container">
                <Button
                  id={`show-more-collection-${collection.id}`}
                  size="extra-small"
                  customWidth={"24px"}
                  type="teritiary-regular"
                  startIcon={MoreHorizontalRegular}
                  onClick={(e) => {
                    rightClickContextMenu();
                  }}
                />
              </span>
            </Tooltip>
          {/if}
        {/if}

        {#if collection?.activeSync && isSyncChangesAvailable && !isSyncing && !isSharedWorkspace}
          <Tooltip
            title={"Changes available for this collection."}
            placement={"top-center"}
            distance={10}
            zIndex={701}
          >
            <CircleSmallFilled color="var(--icon-ds-danger-300)" />
          </Tooltip>
        {:else if isSyncing}
          <Spinner size={"15px"} />
        {/if}
        {#if isActiveSyncEnabled && collection?.activeSync}
          <div style="width: 55px">
            <Tag type="cyan" text={"Sync On"} />
          </div>
          <!-- <Tooltip placement="bottom-center" title="Sync" styleProp="left: 25%;">
          <button
            class="sync-button p-1 border-0 rounded"
            on:click={() => {
              // onRefetchCollection(collection.workspaceId, collection);
              console.log("clciked");
              onCompareCollection(collection.id);
            }}
            on:mouseenter={() => {
              isSyncBtnHovered = true;
            }}
            on:mouseleave={() => {
              isSyncBtnHovered = false;
            }}
          >
            <span
              class="{refreshCollectionLoader
                ? 'refresh-collection-loader'
                : ''}  d-flex justify-content-center align-items-center p-1"
            >
              <ReloadCollectionIcon
                color={isSyncBtnHovered ? "var(--active-sync-btn)" : "grey"}
              />
            </span>
          </button>
        </Tooltip> -->
        {/if}
      {/if}
    </div>
    <!-- {console.log(collection.name, !collection?.activeSync, activeSyncLoad)} -->
    <!-- {#if !collection?.activeSync || activeSyncLoad} -->
    <!-- {#if !collection?.activeSync || isBranchSynced} -->

    {#if visibility}
      <div
        class="z-1 collection-items-area {isForbiddenDrop
          ? 'drag-forbidden'
          : ''}"
        style="padding-left: 0; padding-right:0;"
        on:dragover={handleDragOver}
        on:dragleave={handleDragLeave}
        on:drop={handleDrop}
      >
        <div
          class=" ps-0 position-relative"
          style={`background-color: ${collection.id === activeTabId ? "var(--bg-ds-surface-600)" : "transparent"}; margin-bottom: ${collection.id === activeTabId ? "0px" : "0px"};`}
        >
          {#if isMockCollection}
            <div
              class="box-line"
              style="background-color: {verticalCollectionLine
                ? 'var(--bg-ds-neutral-700)'
                : 'var(--bg-ds-surface-700)'}"
            ></div>
            <div
              style="height:32px; padding-left:68px; color: var(--text-ds-neutral-500)"
              class="d-flex align-items-center text-ds-font-weight-semi-bold"
            >
              <div class="d-flex gap-2 text-ds-font-size-12">
                <div class="d-flex align-items-center">
                  <SettingsRegular size="16px" />
                </div>
                <div>Configuration</div>
              </div>
            </div>
            <div
              class="d-flex align-items-center justify-content-between my-button btn-primary {`mockHistory-${collection.id}` ===
              activeTabId
                ? 'active-history-tab'
                : ''}"
              style="height: 32px; padding-left: 3px;"
            >
              <button
                tabindex="-1"
                on:click={() => {
                  onItemOpened("mockHistory", {
                    workspaceId: collection.workspaceId,
                    collection,
                  });
                }}
                style="padding-left: 29px; height: 100%;"
                class="main-file d-flex align-items-center position-relative bg-transparent border-0"
              >
                <div
                  class="api-method"
                  style="height: 24px; width: 24px !important; margin-right: 2px;"
                ></div>
                <span class="api-method">
                  <HistoryRegular size={"16px"} />
                </span>

                <div class="api-name" style="color: var(--text-ds-neutral-50);">
                  <p
                    class="ellipsis m-0 p-0 text-ds-font-size-12 text-ds-line-height-130 text-ds-font-weight-medium"
                  >
                    History
                  </p>
                </div>
              </button>
            </div>
          {/if}
          <div class="">
            {#if isSyncChangesAvailable && isEnableSyncButton && userRole !== WorkspaceRole.WORKSPACE_VIEWER && !isSharedWorkspace}
              <div class="ps-5" style="height: 32px; ">
                <div
                  style="background-color: var(--bg-ds-primary-800); align-items:center; justify-content:space-between; border-radius:4px;"
                  class="d-flex"
                >
                  <p
                    class="text-ds-font-size-12 text-ds-line-height-150 text-ds-font-weight-medium"
                    style="margin-bottom: 0px; margin-left:6px;"
                  >
                    Changes Available
                  </p>
                  <div class="d-flex">
                    <Button
                      title={"Sync"}
                      type={"link-primary"}
                      loader={false}
                      onClick={() => {
                        console.log("Synced clicked");
                        onSyncCollection(collection.id);
                      }}
                    />
                    <Tooltip
                      placement="top-center"
                      title={"Dismiss"}
                      distance={12}
                    >
                      <Button
                        type={"teritiary-regular"}
                        loader={false}
                        onClick={() => {
                          isEnableSyncButton = false;
                        }}
                        startIcon={DismissRegular}
                      />
                    </Tooltip>
                  </div>
                </div>
              </div>
            {/if}
          </div>
          {#if !collection?.items?.length}
            <p
              class="text-ds-font-size-12 ps-5 ms-2 my-{collection.id ===
              activeTabId
                ? '0'
                : '0'} text-secondary-300"
            >
              {isMockCollection
                ? "This mock collection is empty."
                : "This collection is empty."}
            </p>
          {/if}
        </div>
      </div>
    {/if}
  {/if}
</div>

<style>
  .box-line {
    visibility: none;
  }

  .sync-button {
    background-color: transparent;
  }
  .sync-button:active {
    background-color: var(--editor-angle-bracket);
  }
  .my-button:hover .threedot-icon-container {
    visibility: visible;
  }
  .my-button:hover .add-icon-container {
    visibility: visible;
  }

  .main-file {
    width: calc(100% - 28px);
  }

  .api-method {
    font-size: 10px;
    font-weight: 400;
    width: 30px !important;
    height: 24px;

    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: end;
    padding: 4px;
  }
  .api-name {
    font-weight: 500;
    width: calc(100% - 58px);
    text-align: left;
    font-size: 12px;
    line-height: 18px;
    padding: 2px 4px;
  }

  .active-history-tab {
    background-color: var(--bg-ds-surface-500) !important;
    border-radius: 4px;
  }

  .list-icons {
    width: 16px;
    height: 16px;
    margin-right: 10px;
  }
  .list-icons:hover {
    filter: invert(78%) sepia(86%) saturate(3113%) hue-rotate(177deg)
      brightness(100%) contrast(100%);
  }
  .threedot-icon-container {
    visibility: hidden;
    background-color: transparent;
  }
  .threedot-icon-container:active {
    background-color: var(--bg-secondary-420) !important;
  }

  .threedot-active {
    visibility: visible;
    background-color: var(--bg-tertiary-600);
  }
  .add-icon-container {
    visibility: hidden;
    display: flex;
  }
  .add-icon-container:hover {
  }

  .add-icon-container:active {
    /* background-color: var(--bg-secondary-420) !important; */
  }
  .add-item-active {
    visibility: visible;
    background-color: var(--bg-tertiary-600);
  }
  .refresh-collection-loader-active {
    visibility: visible;
  }
  .threedot-icon-container:hover {
    background-color: var(--bg-tertiary-500);
  }

  .btn-primary {
    background-color: transparent;
    color: var(--text-ds-neutral-50);
    padding-right: 5px;
    border-radius: 2px;
  }

  .btn-primary:hover {
    background-color: var(--bg-ds-surface-400);
    color: var(--text-ds-neutral-50);
    border-radius: 4px;
  }
  .btn-primary:hover .add-icon-container {
    visibility: visible;
  }
  .btn-primary:hover .box-line {
    visibility: visible;
  }

  .box-line {
    position: absolute;
    top: 0;
    bottom: 0%;
    left: 27.5px;
    width: 1px;

    z-index: 1;
  }

  .btn-primary:focus-visible {
    background-color: var(--bg-ds-surface-400);
    color: var(--text-ds-neutral-50);
    outline: none;
    border-radius: 4px;
    border: 2px solid var(--bg-ds-primary-300) !important;
  }
  .btn-primary:active {
    background-color: var(--bg-ds-surface-500);
    color: var(--text-ds-neutral-50);
    outline: none;
    border-radius: 4px;
  }
  .btn-primary:focus-visible .add-icon-container {
    visibility: visible;
  }

  .renameInputFieldCollection {
    border: none;
    background-color: transparent;
    color: var(--bg-ds-neutral-50);
    height: 24px;
    outline: none;
    border-radius: 4px !important;
    padding: 4px 2px;
    caret-color: var(--bg-ds-primary-300);
  }
  .renameInputFieldCollection:focus {
    border: 1px solid var(--border-ds-primary-300) !important;
  }
  .main-collection {
    width: calc(100% - 55px);
  }
  .main-collection-mock {
    width: calc(100% - 100px);
  }
  .main-collection-sync {
    width: calc(100% - 119px);
  }
  .active-collection-tab {
    background-color: var(--bg-ds-surface-500) !important;
    border-radius: 4px;
  }
  .collection-collection-name {
    width: calc(100% - 10px);
    text-align: left;
  }
  .refresh-collection-loader {
    animation: loader-animation 1s linear infinite;
  }
  @keyframes loader-animation {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  .shortcutIcon:hover {
    background: var(--right-border);
  }
  .sub-folders {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 40px;
    width: 1px;
    background-color: var(--bg-ds-surface-100);
  }

  .collection-items-area {
    position: relative;
  }

  /* Forbidden drop cursor and styling */
  .drag-forbidden {
    cursor: not-allowed !important;
  }

  .drag-forbidden * {
    cursor: not-allowed !important;
  }

  /* Valid drop zone styling - blue dashed border overlay */
  .valid-drop-zone {
    position: relative;
  }

  .valid-drop-zone::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(59, 130, 246, 0.1);
    border: 2px dashed rgba(59, 130, 246, 0.6);
    pointer-events: none;
    opacity: 1;
    transition: opacity 0.2s;
    border-radius: 4px;
  }
</style>
